﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace B10_SocketClient
{
    public partial class Form1 : Form
    {

        Socket socketSend;
        public Form1()
        {
            InitializeComponent();
        }

        private void Btn_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                //创建Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipAddr = IPAddress.Parse(tbx_ip.Text);
                IPEndPoint port = new IPEndPoint(ipAddr, Convert.ToInt32(tbx_port.Text));

                //连接server
                socketSend.Connect(port);
                ShowMsg("连接：" + port.ToString() + "成功！");
                Thread thread = new Thread(Recieve);
                thread.IsBackground = true;
                thread.Start();
            }
            catch
            {
                ShowMsg("连接失败，请检查服务器是否启动！");
            }
        }

        void ShowMsg(string str)
        {
            tbx_RecieveArea.AppendText(str + "\r\n");
        }

        private void Btn_sendMsg_Click(object sender, EventArgs e)
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(tbx_sendArea.Text);

            socketSend.Send(buffer);
        }

        void Recieve()
        {
            while (true)
            {
                try
                {
                    //if (socketSend.Poll(10, SelectMode.SelectRead))
                        
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                        break;
                    string s = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketSend.RemoteEndPoint + ": " + s);
                }
                catch
                {
                    break;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (socketSend != null)
                socketSend.Close();
        }
    }
}
